﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Telerik.Sitefinity;
using Telerik.Sitefinity.GenericContent.Model;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Modules.GenericContent;
using Telerik.Sitefinity.Modules.Libraries;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Workflow;
using System.Globalization;

namespace Migration.Classes
{
	public static class MigrationGenericContents
	{
		private static ContentManager m_ContentManager;

		static MigrationGenericContents()
		{
			m_ContentManager = ContentManager.GetManager(MigrationSettings.GenericContentProvider);
		}

		private static void CheckManagers()
		{
			if (m_ContentManager.Provider == null || MigrationSettings.ApplicationRestarted)
			{
				m_ContentManager = ContentManager.GetManager(MigrationSettings.GenericContentProvider);
			}
		}

		public static void ImportGenericContent(Telerik.Sitefinity.Services.Migration.MigrationGenericContent genericContent)
		{
			CheckManagers();

			var language = genericContent.Language;
            var culture = new CultureInfo(language);
            Guid id = genericContent.Id;
			string name = String.Empty;
			if (genericContent.MetaData.ContainsKey("Name") && genericContent.MetaData["Name"] != null)
				name = genericContent.MetaData["Name"].ToString();

			// Check if the generic content already exists
			bool addNewLanguage = false;
			ContentItem checkItem = m_ContentManager.GetItems<ContentItem>().Where(t => t.Id == id).FirstOrDefault();
			if (checkItem != null)
			{
				if (MigrationCultures.IsMultilingual)
				{
					if (checkItem.AvailableLanguages.Contains(language))
					{
						MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableSkipMessage(name, genericContent.Language));
						return;
					}
					else
						addNewLanguage = true;
				}
				else
				{
					MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableSkipMessage(name, String.Empty));
					return;
				}
			}

			ContentItem contentItem;
			if (addNewLanguage)
				contentItem = checkItem;
			else
				contentItem = m_ContentManager.CreateContent(id);

			string genericContentHtml = String.Empty;
			if (genericContent.Content != null)
				genericContentHtml = genericContent.Content.ToString();	
			genericContentHtml = MigrationUrlRewriter.RewriteAlbumUrls(genericContentHtml);

			if (String.IsNullOrEmpty(language))
				contentItem.Content = genericContentHtml;
			else
				contentItem.SetString("Content", genericContentHtml, language);

			foreach (KeyValuePair<string, object> metaData in genericContent.MetaData)
			{
				if (metaData.Value == null)
					continue;

				switch (metaData.Key)
				{
					case "Author":
						contentItem.Author = metaData.Value.ToString();
						break;
					case "Category":
						MigrationTaxonomies.AddCategoryToOrganizer(metaData.Value.ToString(), contentItem.Organizer, culture);
						break;
					case "Description":
						if (String.IsNullOrEmpty(language))
							contentItem.Description = metaData.Value.ToString();
						else
                            contentItem.Description[culture] = metaData.Value.ToString();
						break;
					case "Name":
						contentItem.Name = metaData.Value.ToString();
						if (String.IsNullOrEmpty(language))
							contentItem.Title = contentItem.Name;
						else
                            contentItem.Title[culture] = contentItem.Name;
						break;
					default:
					{
						string metaDataName = metaData.Key;
						var checkField = App.WorkWith().DynamicData().Type(typeof(ContentItem)).Fields().Get().Where(f => f.FieldName == metaDataName).FirstOrDefault();
						if (checkField != null)
						{
							try
							{
								contentItem.SetValue(metaDataName.ToLowerInvariant(), metaData.Value.ToString());
							}
							catch (NullReferenceException) { };
						}
					}
					break;
				}
			}

			contentItem.DateCreated = genericContent.DateCreated;
			contentItem.LastModified = genericContent.DateModified;
			contentItem.Owner = MigrationUsers.DefaultOwner;

			// Add the tags
            MigrationTaxonomies.AddTagsToOrganizer(genericContent.Tags, contentItem.Organizer, culture);

            // Add the URL name
			var urlName = String.Empty;

			if (String.IsNullOrEmpty(language))
				urlName = MigrationUtils.GetUrlName(contentItem.Title);
			else
                urlName = MigrationUtils.GetUrlName(contentItem.Title[culture]);

            var checkUrl = m_ContentManager.GetItems<ContentItem>().Where(t => t.UrlName == urlName).FirstOrDefault();
            if (checkUrl != null)
                urlName = MigrationUtils.GetUrlName(contentItem.Id.ToString());

            if (String.IsNullOrEmpty(language))
                contentItem.UrlName = urlName;
            else
                contentItem.UrlName[culture] = urlName;

			m_ContentManager.RecompileItemUrls<ContentItem>(contentItem);
			m_ContentManager.SaveChanges();

			// Add the comments
			MigrationComments.AddCommentsToGenericContent(contentItem.Id, genericContent.Comments, language);

			MigrationLogger.AppendLogMessage(MigrationUtils.GetLocalizableImportMessage(name, genericContent.Language));
		}
	}
}
